package com.utils;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;

public class MutilFileBakUtil {

    /**
     * @param fileName
     * @param parentPath
     * @param oldFile
     */
    public static void multiBakLogic(String fileName, String parentPath, File oldFile, int bakCount) {
        fileName = fileName + ".";
        String replaceString = ".bak";
        File fileList = new File(parentPath);
        String[] fileNameArr = fileList.list();
        long minFile = Long.MAX_VALUE;
        String recordFileString = null;
        int cotainFileCount = 1;
        for (int i = 0; i < fileNameArr.length; i++) {
            if (fileNameArr[i].contains(fileName)) {
                cotainFileCount++;
                File file = new File(fileNameArr[i]);
                String time = fileNameArr[i].replace(fileName, "").replace(replaceString, "");
                long currentTime = Long.valueOf(time);
                if (currentTime < minFile) {
                    minFile = currentTime;
                    recordFileString = fileNameArr[i];
                }
                System.out.println("contain " + file.getName() + " time:" + time);
            }
        }

        System.out.println("lastcreate " + recordFileString);

        if (cotainFileCount > bakCount) {
            File fileRecord = new File(parentPath + "/" + recordFileString);
            if (fileRecord.exists()) {
                if (fileRecord.delete()) {
                    System.out.println("delete " + fileRecord.getPath());
                }
            }
        }

        SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置日期格式
        String currentTime = df.format(new Date());

        File bakFile = new File(oldFile.getPath() + "." + currentTime + ".bak");
        if (oldFile.renameTo(bakFile)) {
            System.out.println(oldFile.getName() + " rename to " + bakFile.getName());
        }
    }

}
